"""
Case Type   : ustore copy from/to
Case Name   : ustore-copy -null参数
Create At   : 2024-07-25
Owner       : songjing20
Description :
    1.创建ustore表并插入数据
    2.copy to 含null参数
    3.清理环境
Expect      :
    1.执行成功
    2.copy成功
    3.执行成功
History     :
"""
import os
import unittest

from yat.test import Node
from yat.test import macro
from testcase.utils.Logger import Logger
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant


class UstoreCopy(unittest.TestCase):
    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.node_pri = Node('PrimaryDbUser')
        self.constant = Constant()
        self.tb_name = 't_copy_0010'
        self.file_abspath = os.path.join(
            macro.DB_BACKUP_PATH, f"{self.tb_name}.dat")

    def test_copy_from_to(self):
        text = '-----step1:创建ustore表并插入数据;expect:成功-----'
        self.log.info(text)
        sql = f'''drop table if exists {self.tb_name} cascade;
        create table {self.tb_name}(a int,b char(16),c varchar(20),d int)
        with(storage_type=ustore);
        insert into {self.tb_name} values (001,'sk1','tt',3222);
        insert into {self.tb_name} values (002,'sk1','tt',3222);
        insert into {self.tb_name} values (003,'sk1','tt',3222);'''
        sql_res = self.pri_sh.execut_db_sql(sql)
        self.log.info(sql_res)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, sql_res,
                      f'执行失败:{text}')
        self.assertEqual(3, sql_res.count(self.constant.INSERT_SUCCESS_MSG),
                         f'执行失败:{text}')

        text = '-----step2:copy to 含null参数;expect:成功-----'
        self.log.info(text)
        copy_to_res = self.pri_sh.execut_db_sql(
            f"copy  {self.tb_name} to '{self.file_abspath}' "
            f"with(delimiter '/',null '');")
        self.log.info(copy_to_res)
        self.assertIn('COPY 3', copy_to_res, f'执行失败:{text}')
        cmd = f'cat {self.file_abspath};'
        self.log.info(cmd)
        cmd_res = self.node_pri.sh(cmd).result()
        self.log.info(cmd_res)
        self.assertIn('1/sk1             /tt/3222\n'
                      '2/sk1             /tt/3222\n'
                      '3/sk1             /tt/3222', cmd_res, f'执行失败:{text}')

    def tearDown(self):
        text = '-----step3:清理环境;expect:成功-----'
        self.log.info(text)
        drop_res = self.pri_sh.execut_db_sql(
            f"drop table if exists {self.tb_name} cascade;")
        self.log.info(drop_res)
        cmd = f'rm -f {self.file_abspath};echo $?;'
        self.log.info(cmd)
        cmd_res = self.node_pri.sh(cmd).result()
        self.log.info(cmd_res)
        self.assertIn(self.constant.TABLE_DROP_SUCCESS, drop_res,
                      f'删表失败:{text}')
        self.assertEqual('0', cmd_res, f'执行失败:{text}')
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
